class Network {
  constructor () {
    this.SERVER_URL = 'http://vpspbirthdaytest.mooddo.com'
  }

  /**
   * 这里设置全局头部 比如token 等信息
   */
  getHeader () {
    const token = wx.getStorageSync('token')
    return {vp_token: `${token}`}
  }
  // 这里处理请求失败的数据 如果比较多可以写一个配置文件
  failFilter (data) {
    if (data.Code !== 401) {
      wx.showToast({icon: 'none', title: data.Message})
    }
  }

  request (url, data, method = 'GET') {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${this.SERVER_URL}${url}`,
        data,
        header: this.getHeader(),
        method,
        success: res => {
          const data = res.data
          if (data.IsSuccess) {
            return resolve(data.Data)
          }
          reject(this.failFilter(data))
        },
        fail: e => {
          // 异常 直接抛出
          // reject(e)
          throw new Error(e)
        }
      })
    })
  }

  // get请求
  get (url, data) {
    return this.request(url, data, 'GET')
  }

  // post 请求
  post (url, data) {
    return this.request(url, data, 'POST')
  }
};

const network = new Network()
export default network
export const get = url => {
  return sendData => network.get(url, sendData)
}

export const post = url => {
  return sendData => network.post(url, sendData)
}
